/*
    This source file is part of GeNa project.
    Copyright © GeNa project 2008
    For the latest info, see http://code.google.com/p/genaproject/ or  http://lumpyproject.forums-rpg.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>. */

#ifndef OBJECT_H_INCLUDED
#define OBJECT_H_INCLUDED

#include <map>

class Object
{
protected:
	class Conv
	{
    private:
		bool toId;
	public:
        Conv( bool _toId)
        {
            toId = _toId;
        }

		template<class T> void operator() (T* &t)
		{
            if( toId)
            {
                if( t)
                    reinterpret_cast<int&>(t) = t->getId();
            }
            else
            {
                if( t)
                    t = getObject(reinterpret_cast<int&>(t));
            }
		}
	};

	virtual void convert( Conv conv) = 0;
private:
	int id;
public:
	static std::map<int, Object*> env;
	static unsigned int topId;
	inline static unsigned int getNewId();
	inline static Object* getObject(int id);

	Object()
	{
		id = getNewId();
		env[id] = this;
	}

	Object(const Object &obj)
	{
	    id = obj.id;
	}

	Object & operator=(const Object &obj)
	{
	    id = obj.id;
	    return *this;
	}

	virtual ~Object()
	{
	}

	int getId()
	{
	    return id;
	}

	Object* swap()
	{
	    Object* obj = env[id];
	    env[id] = this;
	    return obj;
	}

	void toId()
	{
	    convert( Conv(true));
	}

	void fromId()
	{
	    convert( Conv(false));
	}

	void unlink()
	{
	    env[id] = NULL;
	}

	void link()
	{
	    env[id] = this;
	}

	virtual void copyTo(Object* obj) = 0;
	virtual Object* copy() = 0;
};

template<class T> class ObjectOf : public Object
{
public:
    void copyTo(Object* obj)
    {
        T & t = *dynamic_cast<T*>(obj);
        t = *dynamic_cast<T*>(this);
    }

    Object* copy()
    {
        return new T(*dynamic_cast<T*>(this));
    }
};

unsigned int Object::getNewId()
{
    topId++;
    return topId;
}

Object* Object::getObject(int id)
{
    return env[id];
}

#endif // OBJECT_H_INCLUDED
